<!-- 保险公司编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="800"
    :model-value="modelValue"
    :title="title"
    @update:modelValue="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="130px">
      <el-form-item label="交强险" prop="qx_price">
        <el-input v-model="form.qx_price" disabled style="width: 200px">
          <template #prepend>应收</template>
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="车船税" prop="tax_price">
        <el-input v-model="form.tax_price" disabled style="width: 200px">
          <template #prepend>应收</template>
          <template #append>元</template>
        </el-input>
      </el-form-item>

      <el-form-item label="商业险" prop="syx_price">
        <el-input v-model="form.syx_price" disabled style="width: 200px">
          <template #prepend>应收</template>
          <template #append>元</template>
        </el-input>
      </el-form-item>

      <el-form-item label="其他保险" prop="qtx_price">
        <el-input v-model="form.qtx_price" disabled style="width: 200px">
          <template #prepend>应收</template>
          <template #append>元</template>
        </el-input>
      </el-form-item>

      <el-form-item label="分期手续费" prop="fenqi_charge_amount">
        <el-input
          v-model="form.fenqi_charge_amount"
          disabled
          style="width: 200px"
        >
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="管理费" prop="glf_paid">
        <el-input v-model="form.glf_price" style="width: 200px">
          <template #append>元</template>
        </el-input>
        <el-input
          v-model="form.glf_note"
          style="width: 300px"
          class="ml8"
          placeholder="不收请说明原因"
        />
      </el-form-item>
      <el-form-item label="GPS费" prop="gps_paid">
        <el-input v-model="form.gps_price" style="width: 200px">
          <template #append>元</template>
        </el-input>
        <el-input
          v-model="form.gps_note"
          style="width: 300px"
          class="ml8"
          placeholder="不收请说明原因"
        />
      </el-form-item>
      <el-form-item label="二保费" prop="eb_paid">
        <el-input v-model="form.eb_price" style="width: 200px">
          <template #append>元</template>
        </el-input>
        <el-input
          v-model="form.eb_note"
          style="width: 300px"
          class="ml8"
          placeholder="不收请说明原因"
        />
      </el-form-item>
      <el-form-item label="学习费" prop="xx_paid">
        <el-input v-model="form.xx_price" style="width: 200px">
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="盖章费" prop="gz_paid">
        <el-input v-model="form.gz_price" style="width: 200px">
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="法务费" prop="fw_paid">
        <el-input v-model="form.fw_price" style="width: 200px">
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="其他费用">
        <div
          v-for="(item, index) in qtList"
          :key="item.id"
          style="margin-bottom: 8px"
        >
          <el-input v-model="item.title" style="width: 200px">
            <template #prepend>费用名</template>
          </el-input>
          <el-input v-model="item.price" style="width: 120px" class="ml8">
            <template #append>元</template>
          </el-input>
          <span
            class="blue pointer ml8"
            v-if="index != 0"
            @click="delItem(index)"
          >
            删
          </span>
          <span class="blue pointer ml8" v-if="index == 0" @click="addItem">
            添加
          </span>
        </div>
      </el-form-item>
      <el-form-item label="总计应收" prop="price">
        <el-input v-model="price" disabled style="width: 200px">
          <template #append>元</template>
        </el-input>
      </el-form-item>
    </el-form>
    <template
      #footer
      v-if="form.status == 0 || form.status == 4 || form.status == 3"
    >
      <el-button @click="updateModelValue(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch, computed } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { useFormData } from '@/utils/use-form-data';
  import { updateTradePrice } from '@/api/company';
  import { jsJiafa } from '@/utils/my-common';
  import { ElMessage } from 'element-plus';
  const emit = defineEmits(['done', 'update:modelValue']);

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object
  });

  /** 是否是修改 */
  const isUpdate = ref(false);

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    id: 0,
    status: '',
    tax_price: '',
    qx_price: '',
    syx_price: '',
    qtx_price: '',

    glf_price: '', // 管理费
    glf_note: '', // 管理费
    gps_price: '', // gps
    gps_note: '', // gps
    eb_price: '', // 二保
    eb_note: '', // 二保
    xx_price: '', // 学习
    xx_paid: '', // 学习
    gz_price: '', // 盖章
    gz_paid: '', // 盖章
    fw_price: '', // 法务
    fw_paid: '', // 法务
    qt_price: '', // 其他
    qt_paid: '', // 其他
    fenqi_amount: '',
    dianfu_amount: '',
    fenqi_charge_amount: '',
    price: '', // 总计
    paid: '', // 实际付款
    pay_images: '', // 付款图片
    diff_price: 0,
    diff_price_type: '' // 差价处理方式
  });

  // 计算总计应付
  const price = computed(() => {
    var price = 0;
    price = jsJiafa(price, form.tax_price);
    price = jsJiafa(price, form.qx_price);
    price = jsJiafa(price, form.syx_price);
    // price = jsJiafa(price, form.cpx_price);
    // price = jsJiafa(price, form.cyx_price);
    // price = jsJiafa(price, form.hyx_price);
    // price = jsJiafa(price, form.azx_price);
    // price = jsJiafa(price, form.jyx_price);
    price = jsJiafa(price, form.qtx_price);
    price = jsJiafa(price, form.glf_price);
    price = jsJiafa(price, form.gps_price);
    price = jsJiafa(price, form.eb_price);
    price = jsJiafa(price, form.xx_price);
    price = jsJiafa(price, form.fw_price);
    price = jsJiafa(price, form.gz_price);
    price = jsJiafa(price, form.fenqi_charge_amount);
    price = jsJiafa(price, form.fenqi_first_pay);

    const totalQt =
      qtList.value.reduce((total, item) => {
        // 将金额转换为数字后累加，并乘以 100 以避免精度问题
        return total + Math.round(parseFloat(item.price || 0) * 100);
      }, 0) / 100; // 最后除以 100 恢复原始金额
    price = jsJiafa(price, totalQt);
    return price;
  });

  const qtList = ref([
    {
      title: '',
      price: ''
    }
  ]);

  const addItem = () => {
    qtList.value.push({
      title: '',
      price: ''
    });
  };

  const delItem = (i) => {
    qtList.value.splice(i, 1);
  };

  /** 表单验证规则 */
  const rules = reactive({
    title: [
      {
        required: true,
        message: '请输入保险公司名称',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /** 保存编辑 */
  const save = () => {
    if (!validateFees()) return;
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      // if (diff_price.value != 0 && form.diff_price_type == '') {
      //   ElMessage.warning('请选择差价的处理方式');
      //   return;
      // }
      loading.value = true;
      var requestData = Object.assign({}, form);
      // requestData.paid = paid.value;
      requestData.qtList = JSON.stringify(qtList.value);
      updateTradePrice(requestData)
        .then((msg) => {
          loading.value = false;
          EleMessage.success(msg);
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          EleMessage.error(e.message);
        });
    });
  };

  const validateFees = () => {
    const { glf_price, glf_note, gps_price, gps_note, eb_price, eb_note } =
      form;

    const isEmpty = (val) =>
      val === '' ||
      val === null ||
      val === undefined ||
      val === 0 ||
      val === '0' ||
      val === '0.00';

    if (isEmpty(glf_price) && !glf_note) {
      ElMessage.error('管理费未交，必须填写管理费说明');
      return false;
    }
    if (isEmpty(gps_price) && !gps_note) {
      ElMessage.error('GPS费未交，必须填写GPS费说明');
      return false;
    }
    if (isEmpty(eb_price) && !eb_note) {
      ElMessage.error('二保费未交，必须填写二保费说明');
      return false;
    }

    return true;
  };

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };
  const title = ref('');
  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        title.value = props.data.plate_number + '的实际付款';
        if (props.data) {
          assignFields({
            ...props.data
          });
          qtList.value = props.data.qtList;
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate?.();
      }
    }
  );
</script>
